<?php
namespace system\service;

use herosphp\cache\CacheFactory;
use system\service\interfaces\ISettingService;
use common\service\CommonService;
use herosphp\core\Loader;

Loader::import('system.service.interfaces.ISettingService');

/**
 * system(Service)接口实现
 * @package system\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class SettingService extends CommonService implements ISettingService {

    public function update($data, $id)
    {
        if ( empty($data) ) return false;
        $result = true;
        foreach ( $data as $key => $value ) {
            $result = $result && $this->getModelDao()->replace(array('name' => $key, 'value' => $value));
        }
        $this->flush();
        return $result;
    }

    //获取所有配置
    public function getSettings() {

        $CACHER = CacheFactory::create('file');
        if ( !$CACHER->get(self::SETTING_CACHE_KEY) ) {
            $this->flush();
        }
        return $CACHER->get(self::SETTING_CACHE_KEY);

    }

    /**
     * 获取指定的配置
     * @param $name
     * @return mixed
     */
    public function getSetting($name)
    {
        $item = $this->getItem($name);
        return $item['value'];
    }

    //更新缓存
    protected function flush() {

        $items = $this->getItems();
        $__items = array();
        foreach($items as $value) {
            $__items[$value['name']] = $value['value'];
        }
        $CACHER = CacheFactory::create('file');
        $CACHER->set(self::SETTING_CACHE_KEY, $__items, 0);
    }
}
